package com.crm.service.system.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.constant.StatusConstant;
import com.crm.model.common.dtos.PageResponseResult;
import com.crm.model.common.dtos.ResponseResult;
import com.crm.model.common.enums.AppHttpCodeEnum;
import com.crm.model.system.job.dtos.JobFormDto;
import com.crm.model.system.job.dtos.JobDto;
import com.crm.model.system.job.pojos.Job;
import com.crm.model.system.pojo.User;
import com.crm.service.system.job.mapper.JobMapper;
import com.crm.service.system.job.service.JobService;
import com.crm.service.system.mapper.UserMapper;
import com.crm.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class JobServiceImpl extends ServiceImpl<JobMapper,Job> implements JobService {
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询
     * @param jobDto
     * @return
     */
    @Override
    public PageResponseResult findPage(JobDto jobDto) {
        //校验参数
        jobDto.checkParam();

        //分页+模糊查询
        Page<Job> page = new Page(jobDto.getPage(),jobDto.getSize());

        LambdaQueryWrapper<Job> lqw = new LambdaQueryWrapper<>();
        if (jobDto.getCode() != null && jobDto.getCode().length() > 0){
            lqw.like(Job::getCode,jobDto.getCode());
        }
        if (jobDto.getStatus() != null ){
            lqw.eq(Job::getStatus,jobDto.getStatus());
        }
        if (jobDto.getName() != null && jobDto.getName().length() > 0){
            lqw.like(Job::getName,jobDto.getName());
        }
        page = page(page, lqw);

        //封装响应数据
        PageResponseResult result = new PageResponseResult();
        result.setData(page.getRecords());
        result.setSize((int) page.getSize());
        System.out.println(page.getTotal());
        result.setTotal((int) page.getTotal());
        result.setCurrentPage((int) page.getCurrent());
        return result;
    }

    /**
     * 新增岗位
     * @param jobFormDto
     * @return
     */
    @Override
    public ResponseResult<String> add(JobFormDto jobFormDto) {
        //校验参数
        if (jobFormDto.getName().length()>12 || jobFormDto.getName().length()<1 ||
                jobFormDto.getName()==null ||
                jobFormDto.getDescription().length()>50){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Job job = jobMapper.selectOne(new LambdaQueryWrapper<Job>().eq(Job::getName, jobFormDto.getName()));
        if (job != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        if (jobFormDto.getStatus() == null){
            jobFormDto.setStatus(StatusConstant.JOB_ENABLE_STATUS);
        }

        //添加数据
        try {
            job = new Job();
            BeanUtils.copyProperties(jobFormDto,job);

            //根据name生成岗位编码
            String code = generateCodeByName(jobFormDto.getName());

            job.setCode(code);
            job.setOrders(job.getId());
            job.setCreateUser(ThreadLocalUtil.getUser().getName());
            job.setUpdateUser(ThreadLocalUtil.getUser().getName());
            job.setCreateTime(LocalDateTime.now());
            job.setUpdateTime(LocalDateTime.now());

            jobMapper.insert(job);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        } catch (UnsupportedEncodingException e) {
            log.info("岗位编码生成失败:" + e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

    /**
     * 删除岗位
     * @param id
     * @return
     */
    @Override
    public ResponseResult<String> delete(Integer id) {
        //校验数据
        Job job = jobMapper.selectById(id);
        if (job == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //岗位是否被使用
        if (job.getStatus()==StatusConstant.JOB_ENABLE_STATUS){
            List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getPost, job.getName()));
            if (users.size() != 0){
                return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
            }
        }

        jobMapper.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id查询岗位
     * @param id
     * @return
     */
    @Override
    public ResponseResult<Job> findById(Integer id) {
        Job job = jobMapper.selectById(id);
        return ResponseResult.okResult(job);
    }

    /**
     * 修改岗位信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<String> update(JobFormDto dto) {
        //校验参数
        if (dto.getName().length()>12 || dto.getName().length()<1 ||
                dto.getName()==null ||
                dto.getDescription().length()>50){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Job job = jobMapper.selectById(dto.getId());
        if (job == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        job.setName(dto.getName());
        job.setStatus(dto.getStatus());
        job.setDescription(dto.getDescription());

        try {
            jobMapper.updateById(job);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }

    /**
     * 根据岗位名称生成岗位编码
     * @param name
     * @return
     */
    private String generateCodeByName(String name) throws UnsupportedEncodingException {
        // 用默认字符编码解码字符串。
        byte[] bs = name.getBytes();
        // 用新的字符编码生成字符串
        return new String(bs, "US-ASCII");

    }
}
